import AMapLoader from "@amap/amap-jsapi-loader";
import { Button, Modal, message } from "antd";
import React, { memo, useEffect, useRef, useState } from "react";
import styled from "styled-components";
import AirBarEcharts from "./components/AirBarEcharts";
import AirPieECharts from "./components/AirPieECharts";
import TimelineController from "./components/DateController";
import HumiECharts from "./components/HumiECharts";
import Line from "./components/Line";
import TempECharts from "./components/TempECharts";
import EchartsLeft from "./EchartsLeft";
import EchartsRight from "./EchartsRight";
import bottomicon from "./images/bottomicon.png";
import corrode from "./images/corrode.png";
import corrodeing from "./images/corrodeing.png";
import leavl from "./images/leavl.png";
import lefticon from "./images/lefticon.png";
import locationPng from "./images/location.png";
import point from "./images/point.png";
import righticon from "./images/righticon.png";
import searchLeft from "./images/searchLeft.png";
// import searchicon from "./images/searchpng.png";
import searchRight from "./images/searchRight.png";
import titleicon from "./images/titleicon.png";
const LeftEchartsStyle = {
  width: "306px",
  height: "670px",
  backgroundColor: "rgba(2, 16, 25, 0.9)",
  top: "20px",
  left: "2.5%",
  zIndex: 100,
};
const RightEchartsStyle = {
  width: "306px",
  height: "670px",
  backgroundColor: "rgba(2, 16, 25, 0.9)",
  top: "20px",
  right: "2.5%",
  zIndex: 100,
};
const latlngStyle = {
  backgroundColor: "rgba(2, 16, 25, 0.9)",
  display: "flex",
  justifyContent: "space-between",
  position: "absolute",
  bottom: "10%",
  left: "2.5%",
  zIndex: 100,
  width: "306px",
  padding: "5px 20px",
  color: "#fff",
  fontSize: "14px",
};
const EchartsStyle = {
  position: "absolute",
  padding: "20px",
  border: "2px solid rgba(46,49,63,0.39)",
  borderTop: "8px solid #2f374b",
};

const searchBox = {
  position: "absolute",
  top: "5%",
  zIndex: 100,
  display: "flex",
  alignItems:"center"
};

const Lvavl = {
  position: "absolute",
  
  bottom: "10%",
  right: "2.4%",
  zIndex: 100,
  width: "346px",
};
const inputBoxStyle = {
  display: "flex",
};
const inputStyle = {
  backgroundColor: "rgba(2, 16, 25, 0.7)",
  // height: "38px",
  border: "none",
  width: "400px",
  color: "#fff",
  marginLeft: "10px",
  marginRight: "10px",
  fontSize: "16px",
};
const corrodeStyle = {
  width: "160px",
  // height: "40px",
  cursor: "pointer",
};
// 添加全局样式或使用 styled-components
const CustomModalWrapper = styled.div`
  .ant-modal-content {
    border: 2px solid rgba(46, 49, 63, 0.39);
    border-top: 8px solid #2f374b;
    box-shadow: none;
    padding: 20px;
    width: 390px;
    background-color: rgba(2, 16, 25);
    border-radius: 0;
  }

  .ant-modal-close:hover .ant-modal-close-x {
    color: #fff;
  }
  .ant-modal-close {
    color: #fff;
  }

  .ant-modal-body {
    padding: 0;
  }
  .amap-logo {
    display: none;
    opacity: 0 !important;
  }
`;
// 如果使用高德热力图就在index.js文件渲染此组件
const AMapHome = () => {
  const mapRef = useRef(null);
  const airData = useRef({});
  const [airDatajson, setAirDatajson] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isOpen, setIOpen] = useState(false);
  const [address, setAddress] = useState({
    province: "",
    city: "",
    district: "",
  });
  const [latlngText, setLatlngText] = useState({ lat: "", lng: "" });
  const [AMapInstance, setAMapInstance] = useState(null);
  const [heatInstance, setHeatInstance] = useState(null);
  const [map, setMap] = useState(null);
  const [searchValue, setSearchValue] = useState("");
  const [playHeatData, setplayHeatData] = useState();
  const [heightVh, setHeightVh] = useState(false);
  const [showheat, setShowheat] = useState(false);
  const [datejson, setdatejson] = useState();
  const [bulePosi, setBulePosi] = useState();
  const showModal = () => {
    setIsModalOpen(true);
    setIOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  useEffect(() => {
    const windowInnerHeight = window.innerHeight;

    if (windowInnerHeight === 1200) {
      setHeightVh(true);
    }
    const loadData = async () => {
      // const formattedDate = dayjs().format("YYYY-MM-DD");
        const formattedDate = "2025-02-20";
      try {
        // 初次的进入加载当天数据
        const url = `/data/${formattedDate}.json`;
        const airResponse = await fetch(url);

        const airdata = await airResponse.json();
        const defaultPosition = airdata.slice(178550);
        setBulePosi(defaultPosition);
        setplayHeatData(airdata);
        setAirDatajson(airdata);
        const Geojson = getGeojson(airdata);
        setdatejson(Geojson);

        // 同时更新 ref 以在回调中使用最新数据
      } catch (error) {
        console.error("加载数据失败:", error);
      }
    };
    loadData();
  }, []);

  useEffect(() => {
    window._AMapSecurityConfig = {
      securityJsCode: "26a92ea8558ac6c5138edae8fa8fc6ef",
    };
    if (datejson) {
      AMapLoader.load({
        key: "fcc2a957caedc4be773e3862d24fdcb4",
        version: "2.0",
        plugins: ["AMap.Geocoder"],
        Loca: {
          version: "2.0.0",
        },
      })

        .then((AMap) => {
          const map = new AMap.Map(mapRef.current, {
            zoom: 5,
            center: [116.397428, 39.90923],
            zooms: [4, 8], // 限制缩放范围：[最小级别, 最大级别]
            // mapStyle: "amap://styles/darkblue",
          });
          const districtLayer = new AMap.DistrictLayer.Country({
            zIndex: 10,
            SOC: "CHN",
            depth: 1,
            styles: {
              "nation-stroke": "#22ffff",
              "coastline-stroke": "#22ffff",
              "province-stroke": "#22ffff",
              fill: "#062134", 
            },
          });
          map.add(districtLayer);
          var loca = new window.Loca.Container({
            map,
          });
          var geo = new window.Loca.GeoJSONSource({
            data: datejson,
          });
          var heatmap = new window.Loca.HeatMapLayer({
            // loca,
            zIndex: 10,
            opacity: 1,
            visible: true,
            zooms: [2, 22],
          });

          heatmap.setSource(geo, {
            radius: 15000,
            unit: "meter",
            height: 80,
            difference: true,
            gradient: {
              1: "rgba(255,56,29,0.9)",
              0.8: "rgba(255,174,0,0.8)",
              0.6: "rgba(252,255,0,0.6)",
              0.5: "rgba(114,255,0,0.4)",
              0.4: "rgba(0,255,132,0.2)",
              0.2: "rgba(170,255,0,0.9)",
            },
            value: function (index, feature) {
              return feature.properties.count 
            },
            opacity: [0, 1],
            heightBezier: [0, 0.53, 0.37, 0.98],
          });
          // 添加到地图上
          heatmap.hide();
          loca.add(heatmap);
          setHeatInstance(heatmap);
          setAMapInstance(AMap);
          setMap(map);
          bulePosi.forEach(function (item, index) {
            var marker = new AMap.Marker({
              position: [item.long, item.lat],
              icon: point,
              map: map,
            });

            map.add(marker);

            marker.on("click", function (e) {
              // 点击定位点
              const { lnglat } = e;
              setLatlngText({
                lat: lnglat.lat,
                lng: lnglat.lng,
              });

              findlatlng(lnglat, airDatajson);
              getprovinceCity(AMap, lnglat);
              showModal();
            });
          });

          const clickHandler = async (e) => {
            const { lnglat } = e;
            console.log(lnglat, "随机点");
            setLatlngText({
              lat: lnglat.lat,
              lng: lnglat.lng,
            });
            try {
              await getprovinceCity(AMap, lnglat);

              findlatlng(lnglat, airDatajson);
              // showModal();
              setIOpen((prev) => !prev);
            } catch (error) {
              message.warning(error.message);
            }
          };
          map.on("click", clickHandler); // 点击任一点
        })
        .catch((e) => {
          console.error("地图加载失败:", e); // 添加错误日志
        });
    }
  }, [datejson]); // 移除不必要的依赖

  /**
   * 根据经纬度获取省、市、区信息
   * @param {Object} AMap - 高德地图实例
   * @param {Object} lnglat - 经纬度对象
   */

  function getprovinceCity(AMap, lnglat) {
    return new Promise((resolve, reject) => {
      const getlnglat = [lnglat.lng, lnglat.lat];
      var geocoder = new AMap.Geocoder();
      // 根据坐标逆地理编码
      geocoder.getAddress(getlnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          const addressComponent = result?.regeocode?.addressComponent;
          const { province, city, district } = addressComponent;
          // 设置地址信息

          setAddress({
            province,
            city,
            district,
          });
          resolve(addressComponent);
        } else {
          reject(new Error("获取地址失败,不是中国境内"));
        }
      });
    });
  }

  // 定义一个函数来计算两点之间的欧几里得距离

  const calculateDistance = (lat1, lng1, lat2, lng2) => {
    return Math.sqrt(Math.pow(lat1 - lat2, 2) + Math.pow(lng1 - lng2, 2));
  };

  function findlatlng(evenlnglat, data) {
    let minDistance = Infinity;
    let closestData = null;
    // 遍历数据数组
    for (let i = 0; i < data.length; i++) {
      const currentData = data[i];
      const distance = calculateDistance(
        evenlnglat.lat,
        evenlnglat.lng,
        currentData.lat,
        currentData.long
      );

      if (distance < minDistance) {
        minDistance = distance;
        closestData = currentData;
      }
    }
    airData.current = closestData;
  }

  const handleSearch = async () => {
    //搜索规则 先输入纬度，再输入经度
    // lat: 31.140715
    // lng: 121.525852  上海

    // lat: 39.853125;
    // lng: 116.459572; 北京
    // const isLatLngV = "39.904179,116.407387"
    // // const isLatLngV = "22.73877149,108.41760246"
    if (!searchValue || !AMapInstance) {
      message.warning("请输入搜索内容");
      return;
    }
    console.log(searchValue, "searchValue");
    // 判断输入是否为经纬度格式
    const isLatLng =
      /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/.test(
        searchValue
      );
    console.log(isLatLng, "isLatLng");
    if (isLatLng) {
      const [lat, lng] = searchValue.split(",").map(Number);
      console.log(lat, lng);
      const lnglat = {
        lat: lat,
        lng: lng,
      };
      try {
        await getprovinceCity(AMapInstance, lnglat);
      } catch (error) {
        message.error("经纬度错误或不在中国境内");
        return;
      }
      // 如果是经纬度格式，直接解
      console.log("pppp");
      map.setCenter([lng, lat]);
      map.setZoom(8);

      var marker = new AMapInstance.Marker({
        position: [lng, lat], // 标记位置
        icon: locationPng,
        map: map, // 将标记添加到地图上
      });
      map.add(marker);
      setLatlngText({
        lat,
        lng,
      });
      marker.on("click", function (e) {
        // 点击定位点
        const { lnglat } = e;
        console.log(lnglat, "lnglat");

        findlatlng(lnglat, airDatajson);
        getprovinceCity(AMapInstance, lnglat);
        setIOpen((prev) => !prev);
      });
    } else {
      // 如果不是经纬度格式，使用地址解析
      console.log("如果不是经纬度格式，使用地址解析");
      const geocoder = new AMapInstance.Geocoder();
      try {
        console.log("如果不是经纬度格式，使用地址解析===", geocoder);
        const result = await new Promise((resolve, reject) => {
          geocoder.getLocation(searchValue, (status, result) => {
            if (status === "complete") {
              console.log(status, "----", searchValue);
              if (result.geocodes && result.geocodes.length > 0) {
                resolve(result);
              } else {
                reject(new Error("未找到该地址"));
              }
            } else {
              reject(new Error("地址解析失败"));
            }
          });
        });
        console.log(result, "result");
        const { location } = result.geocodes[0];
        map.setCenter([location.lng, location.lat]);
        map.setZoom(8);

        const marker = new AMapInstance.Marker({
          position: [location.lng, location.lat], // 标记位置
          icon: locationPng,
          map: map, // 将标记添加到地图上
        });
        map.add(marker);
        setLatlngText({
          lat: location.lat,
          lng: location.lng,
        });
        marker.on("click", function (e) {
          // 点击定位点
          const { lnglat } = e;
          console.log(lnglat, "lnglat");

          findlatlng(lnglat, airDatajson);
          getprovinceCity(AMapInstance, lnglat);
          setIOpen((prev) => !prev);
        });
      } catch (error) {
        message.error("搜索失败,请正确输入地名或者经纬度");
      }
    }
  };

  const getGeojson = (data) => ({
    type: "FeatureCollection",
    features: data.map(({ long, lat, i }) => ({
      type: "Feature",
      geometry: {
        type: "Point",
        coordinates: [long, lat],
      },
      properties: {
        count: i,
      },
    })),
  });
  const ChangeSource = (chunk) => {
    const Geojson = getGeojson(chunk);

    var geo = new window.Loca.GeoJSONSource({
      data: Geojson,
    });
    heatInstance.show();
    heatInstance.setSource(geo, {
      radius: 15000,
      unit: "meter",
      height: 8000,
      difference: true,
      gradient: {
        1: "rgba(255,56,29,1.0)",
        0.8: "rgba(255,174,0,0.8)",
        0.6: "rgba(252,255,0,0.6)",
        0.5: "rgba(114,255,0,0.4)",
        0.4: "rgba(0,255,132,0.2)",
        0.2: "rgba(170,255,0,0.9)",  
      },
      value: function (index, feature) {
        return feature.properties.count ;
      },
      opacity: [0, 1],
      heightBezier: [0, 0.53, 0.37, 0.98],
    });
  };

  const handleCorrode = () => {
    setShowheat((prevShowheat) => !prevShowheat);

    if (!showheat) {
      heatInstance.show();
    } else {
      heatInstance.hide();
    }
  };
  const ModalTitle = memo(() => {
    return (
      <div style={{ display: "flex", alignItems: "center" }}>
        <img
          src={titleicon}
          alt=""
          style={{ width: "12px", height: "12px", marginRight: "10px" }}
        />
        <div style={{ color: "#FFF" }}>
          {address.province}
          {address.city}
          {address.district}
        </div>
      </div>
    );
  });

  return (
    <div
      ref={mapRef}
      style={{
        width: "100%",
        height: heightVh ? "100vh" : "900px",
        display: "flex",
        justifyContent: "center",
      }}
    >
      <div style={searchBox}>
        <div style={inputBoxStyle}>
          <img src={searchLeft} alt="" style={{ height: "38px" }} />
          <input
            style={inputStyle}
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            placeholder="请输入地点名称或经纬度"
            className="search-input"
          />
          <img src={searchRight} alt="" style={{ height: "38px" }} />
        </div>

        <Button
          type="primary"
          onClick={handleSearch}
          style={{
            height: "38px",
            width: "72px",
            marginRight: "10px",
            marginLeft: "10px",
            borderRadius:"0px"
          }}
        >
          搜索
        </Button>

        <img
          src={showheat ? corrodeing : corrode}
          alt=""
          onClick={handleCorrode}
          style={corrodeStyle}
        />
      </div>

      <Modal
        open={isModalOpen}
        footer={null}
        onCancel={handleCancel}
        wrapClassName="custom-modal" // 添加自定义类名
        modalRender={(node) => <CustomModalWrapper>{node}</CustomModalWrapper>}
      >
        <div>
          <ModalTitle />
          <div style={{ display: "flex" }}>
            <AirPieECharts airData={airData.current} />
            <TempECharts temp={airData.current.temp} />
            <HumiECharts humi={airData.current.humi} />
          </div>
          <div>
            <AirBarEcharts airData={airData.current} />
          </div>
        </div>
      </Modal>
      {(isOpen || isModalOpen) && (
        <div style={{ ...LeftEchartsStyle, ...EchartsStyle }}>
          <EchartsLeft airData={airData.current} />
        </div>
      )}
      {(isOpen || isModalOpen) && (
        <div style={{ ...RightEchartsStyle, ...EchartsStyle }}>
          <EchartsRight airData={airData.current} />
        </div>
      )}

      <div>
        <div style={Lvavl}>
          <img src={leavl} alt="" />
        </div>
      </div>
      <Line />
      <div style={latlngStyle}>
        <div>纬度: &nbsp; {latlngText.lat || 39.90923}</div>
        <div>经度: &nbsp; {latlngText.lng || 116.397428}</div>
      </div>
      <TimelineController
        playHeatData={playHeatData}
        ChangeSource={ChangeSource}
      />

      <img
        src={bottomicon}
        alt=""
        style={{
          position: "absolute",
          bottom: "35px",
          zIndex: 10,
        }}
      />

      <img
        src={lefticon}
        alt=""
        style={{
          position: "absolute",
          bottom: "100px",
          zIndex: 10,
          left: "5px",
        }}
      />
      <img
        src={righticon}
        alt=""
        style={{
          position: "absolute",
          bottom: "100px",
          zIndex: 10,
          right: "5px",
        }}
      />
    </div>
  );
};

export default AMapHome;
